const { stuModel, classModel } = require('../../model');
const number = require('../../services/learn_number');
const { getResultToObject } = require('../../services/utils');
const tokens = require('../../services/tokenService');

module.exports = {
  create: function (req, res) {
    const org = req.decode.org;
    const { name, password, grade } = req.body;

    number.setCustomerType('stu',function (number) {
      const config = {
        name: name,
        learn_number: number,
        password: password,
        grade: grade,
        org: org,
        updatedAt: Date.now(),
        createdAt: Date.now()
      };

      stuModel.create(config).then(response => {
        return res.send({
          code: 20000
        });
      }).catch(err => {
        console.log(err);
        return res.send({
          code: 10000
        });
      })
    });
  },
  list: function (req, res) {
    const { name, classID, sort, page = 1, limit = 20 } = req.query;
    const attributes = ['id','name','learn_number','grade','createdAt'];
    const where = {org: req.decode.org};

    if (!classID) {
      return res.send({
        code: 10000
      });
    }
    if (classID === '-1'){
      console.log('返回完整表格')
      stuModel.findByFilter(
        attributes,
        where
      ).then(result => {
        event.success(result);
      }).catch(err => {
        event.error(err);
      })
    } else {
      console.log('按班级id查询')
      classModel.findByRelation(['id'], {id: classID},
        {
          model: stuModel.getModel(),
          attributes: attributes
        }
      ).then(result => {
        const list = getResultToObject(result, 'students', attributes);
        if (list.length === 0) {
          return res.send({
            code: 20000,
            data: {
              total: 0,
              items: []
            }
          });
        }
        event.success(list);
      }).catch(err => {
        event.error(err);
      });
    }

    const event = {
      success: function(result){
        const List = result;
        // 条件过滤
        let mockList = List.filter(item => {
          return !(name && item.name.indexOf(name) < 0);
        });
        // 按id从大到小排序
        if (sort === '-id') {
          mockList = mockList.reverse()
        }
        // 限制数量
        const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1));
        return res.send({
          code: 20000,
          data: {
            total: List.length,
            items: pageList
          }
        });
      },
      error: function (err) {
        console.log(err);
        return res.send({
          code: 10000,
          message: '学生列表查询失败'
        });
      }
    }
  }
};
